package com.spider.page;

import com.spider.pool.UriQueueScheduler;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author β世界 on 9:15 2021/5/8
 * Created on 9:15
 * @Description 每个结果类的基类
 **/
@SuppressWarnings("unused")
public abstract class ResultPage {
    protected URL url;
    protected UriQueueScheduler uriQueueScheduler;
    protected String contentType;
    protected Header[] responseHeader;
    protected ResultItem resultItem;

    protected ResultPage(CloseableHttpResponse response, HttpRequestBase httpRequestBase, UriQueueScheduler uriQueueScheduler) {
        this.uriQueueScheduler = uriQueueScheduler;
        try {
            // 封装响应内容
            this.contentType = response.getEntity().getContentType().getValue();
            this.responseHeader = response.getAllHeaders();
            url = httpRequestBase.getURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    protected void setUriQueueScheduler(UriQueueScheduler uriQueueScheduler){
        this.uriQueueScheduler = uriQueueScheduler;
    }

    /**
     * 设置一个结果的存储空间
     * @author Administratorr
     * @date 15:17 2021/6/21
     * @param resultItem: 结果存储空间
     **/
    public void setResultItem(ResultItem resultItem){
        this.resultItem = resultItem;
    }

    /**
     * 获取上下文
     * @author β世界 on 9:20 2021/5/10
     * @return java.lang.String
     **/
    public abstract Object getContent();

    /**
     * 获取响应的类似
     * @author β世界 on 10:27 2021/5/8
     * @return void
     **/
    public String getResponseType(){
        return contentType;
    }

    /**
     * 获取一个响应头的信息
     * @author β世界 on 10:35 2021/5/8
     * @param head: 响应头名字
     * @return java.util.List<org.apache.http.Header>
     **/
    public List<Header> getHeaders(String head){
        List<Header> headers = new ArrayList<>();
        for (Header header : responseHeader) {
            if (header.getName().equals(head)) {
                headers.add(header);
            }
        }
        return headers;
    }

    /**
     * 获取所有的响应头信息
     * @author β世界 on 10:38 2021/5/8
     * @return org.apache.http.Header[]
     **/
    public Header[] getResponseHeader(){
        return responseHeader;
    }

    /**
     * 用于添加未处理的链接到链接管理池
     * @author β世界 on 10:33 2021/5/8
     * @param url: URL
     * @return void
     **/
    public void addUntreated(String url){
        uriQueueScheduler.addUrl(url);
    };

    /**
     * 获取当前页面的url
     * @author β世界 on 8:48 2021/5/11
     * @return java.net.URL
     **/
    public URL getUrl(){
        return url;
    }

}
